<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <common-item1
          :query="query"
          :streetList="streetList"
          :communityList="communityList"
          :villageList="villageList"
          @visibleChangeStreet="visibleChangeStreet"
          @changeStreet="changeStreet"
          @visibleChangeCommunity="visibleChangeCommunity"
          @changeCommunity="changeCommunity"
          @visibleChangeVillage="visibleChangeVillage"
          @changeVillage="changeVillage"
          :show="false"
          :showInput="showInput"
          @search="handleSearch"
        />
        <el-select
          v-model="query.orderStatus"
          placeholder="状态选择"
          class="handle-select mr10"
          @change="change"
          clearable
        >
          <el-option
            v-for="(item, index) in orderStatusArr"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>

        <el-input
          v-model="query.consignee"
          placeholder="收件人"
          class="handle-input mr10"
        ></el-input>
        <el-input
          v-model="query.mobile"
          placeholder="联系电话"
          class="handle-input mr10"
        ></el-input>

        <div class="block" style="float: left; margin-right: 10px;">
          <el-date-picker
            v-model="value2"
            type="daterange"
            align="left"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>

        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="omPermissions.includes('product:order:delete')"
          >删除</el-button
        >
        <el-button
          type="default"
          class="handle-del"
          @click="exportExcel"
          v-if="omPermissions.includes('product:order:export')"
          >导出</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="orderNo"
          label="订单号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="consignee"
          label="姓名"
        ></el-table-column>
        <el-table-column label="商品详情" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleFindDetail(scope.$index, scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="totalAmount"
          label="消费总积分"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="收货地址"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="createDate"
          label="下单时间"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="receiveTime"
          label="完成时间"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="
                scope.row.orderStatus == 0 &&
                  omPermissions.includes('product:order:update')
              "
              @click="handleEdit(scope.$index, scope.row, 1)"
              >发货</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row, 3)"
              v-if="
                (scope.row.orderStatus == 20 || scope.row.orderStatus == 21) &&
                  omPermissions.includes('product:order:update')
              "
              >同意取消</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row, 5)"
              v-if="
                (scope.row.orderStatus == 20 || scope.row.orderStatus == 21) &&
                  omPermissions.includes('product:order:update')
              "
              >拒绝取消</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row, 4)"
              v-if="
                scope.row.orderStatus == 1 &&
                  omPermissions.includes('product:order:update')
              "
              >确认收货</el-button
            >

            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="
                (scope.row.orderStatus == 4 || scope.row.orderStatus == 3) &&
                  omPermissions.includes('product:order:delete')
              "
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 商品详情弹出框 -->
    <el-dialog
      title="商品详情"
      :visible.sync="commodityDetailVisible"
      width="70%"
    >
      <div class="container">
        <el-table
          :data="commodityDetail"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
        >
          <el-table-column label="头像(查看大图)" align="center">
            <template slot-scope="scope">
              <el-image
                class="table-td-thumb"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="名称"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="purchaseQuantity"
            label="数量"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="integral"
            label="使用积分"
          ></el-table-column>
        </el-table>
        <p class="totalIntegral">总积分: {{ totalIntegral }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import NProgress from "nprogress";
import { commonItem1 } from "../../common/commonItem1/common-item1.js";
import util from "utils/util";
import { mapGetters } from "vuex";
export default {
  name: "ordermanage",
  data() {
    return {
      orderStatusArr: [
        "待发货",
        "待收货",
        "取消审核中",
        "已取消",
        "已完成订单",
      ],
      omPermissions: [],
      orderStatus: 0,
      query: {
        // address: "",
        pageIndex: 1,
        pageSize: 20,
        orderStatus: "",
        streetId: "",
        streetName: "",
        communityId: "",
        communityName: "",
        villageId: "",
        villageName: "",
      },
      streetList: [],
      communityList: [],
      villageList: [],
      value2: "",
      showInput: true,
      tableData: [],
      multipleSelection: [],
      delList: [],
      commodityDetailVisible: false,
      pageTotal: 0,
      idx: -1,
      commodityDetail: [],
      totalIntegral: 0,
      ids: [],
    };
  },
  created() {
    this.getData();
    this.omPermissions = this.permissions;
  },
  components: {
    "common-item1": () => import("../../common/commonItem1/common-item1.vue"),
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/order-manage") {
        this.omPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.omPermissions = newVal;
    },
  },
  methods: {
    ...commonItem1,
    getData() {
      // 获取数据
      this.getOrderManage();
    },
    change(value) {
      console.log(value);
      this.$set(this.query, "pageIndex", 1);
      this.$set(this.query, "orderStatus", value);
      this.getOrderManage();
    },
    getOrderManage() {
      this.$axios
        .get("/product/order/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,
            orderStatus: this.query.orderStatus,
            subDistrictId: this.query.streetId,
            communityId: this.query.communityId,
            villageId: this.query.villageId,

            consignee: this.query.consignee,
            mobile: this.query.mobile,
            startDate: this.value2 ? this.value2[0].getTime() : "",
            endDate: this.value2
              ? (
                  this.value2[1].getTime() +
                  (24 * 3600 * 1000 - 1000)
                ).toString()
              : "",
          },
        })
        .then(({ data: res }) => {
          console.log("订单管理", res);
          if (res.code !== 0) {
            return;
          }
          this.tableData = [];
          this.pageTotal = res.data.total;
          this.tableData = res.data.list;

          this.tableData.map((item, index) => {
            var pageIndex = this.query.pageIndex;
            item.index = index + 1 + (pageIndex - 1) * this.query.pageSize;
            item.createDate = this.dateFormat(item.createDate);
            if (item.receiveTime != null) {
              item.receiveTime = this.dateFormat(item.receiveTime);
            }
          });
        })
        .catch(() => {});
    },

    handleFindDetail(index, row) {
      console.log(index, row);
      this.commodityDetailVisible = true;
      this.$axios
        .get("/product/orderitem/page", {
          params: {
            id: row.id,
          },
        })
        .then(({ data: res }) => {
          console.log("商品详情", res);
          if (res.code !== 0) {
            return;
          }
          this.commodityDetail = res.data;
          // 计算总积分
          this.calcTotalIntegral(this.commodityDetail);
        })
        .catch(() => {});
    },
    calcTotalIntegral(commodityDetail) {
      this.totalIntegral = 0;
      commodityDetail.map((item) => {
        this.totalIntegral +=
          parseInt(item.integral) * parseInt(item.purchaseQuantity);
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(
        this,
        "/product/order",
        index,
        this.ids,
        this.getOrderManage
      );
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    exportExcel() {
      this.$axios
        .get("/product/order/export", {
          params: {
            orderStatus: this.query.orderStatus,
            subDistrictId: this.query.streetId,
            communityId: this.query.communityId,
            villageId: this.query.villageId,

            consignee: this.query.consignee,
            mobile: this.query.mobile,
            startDate: this.value2 ? this.value2[0].getTime() : "",
            endDate: this.value2
              ? (
                  this.value2[1].getTime() +
                  (24 * 3600 * 1000 - 1000)
                ).toString()
              : "",
          },
          responseType: "blob",
        })
        .then((res) => {
          const link = document.createElement("a");
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          // let num = "";
          // for (let i = 0; i < 10; i++) {
          //   num += Math.ceil(Math.random() * 10);
          // }
          link.setAttribute(
            "download",
            "订单 " + this.dateFormat(Date.now(), "yyyy-mm-dd") + ".xls"
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {});
    },
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(this, "/product/order", "", ids, this.getOrderManage);
    },
    // 选择状态
    // changeOrderStatus(value) {
    //   this.mustSelect = false;
    //   console.log(value);
    //   this.editForm.orderStatus = value;
    // },
    // 编辑操作
    handleEdit(index, row, value) {
      console.log(index, row, value);

      // return;
      this.idx = index;
      // this.form = row;
      // this.editVisible = true;

      this.$axios
        .get(`product/order/${row.id}`)
        .then(({ data: res }) => {
          console.log(res);
          if (res.code != 0) {
            return;
          }
          // this.orderStatus = res.data.orderStatus;
          this.editForm = res.data;
          this.editForm.orderStatus = value;
          console.log(this.editForm);
        })
        .catch(() => {});

      // 二次确认
      this.$confirm("确定操作吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          // this.$message.success("删除成功");
          // this.tableData.splice(index, 1);
          this.saveEdit();
        })
        .catch(() => {});
    },
    // 保存编辑
    saveEdit() {
      // if (this.mustSelect) {
      //   return this.$message.error("请选择一种状态");
      // }
      // this.mustSelect = true;

      // this.editVisible = false;
      this.orderStatus = null;
      // 得到成功提示
      this.$axios
        .put("/product/order", {
          id: this.editForm.id,
          orderStatus: this.editForm.orderStatus,
          userId: this.editForm.userId,
          payAmount: this.editForm.payAmount,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getOrderManage();
        })
        .catch(() => {});
    },
    // 分页导航
    handlePageChange(val) {
      console.log(val);
      this.$set(this.query, "pageIndex", val);

      this.getData();
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getOrderManage();
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
  width: 120px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.totalIntegral {
  text-align: right;
  padding-top: 20px;
}
</style>
